package com.example.gui;

import com.example.dao.AdminDAO;
import com.example.model.CardInfo;
import com.example.model.UserInfo;
import com.example.util.CardTableModel;
import com.example.util.UserTableModel;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class CardManagementPanel extends JPanel {

    static AdminDAO adminDAO = new AdminDAO();
    CardTableModel tableModel;
    JTable cardTable;
    List<CardInfo> cardData;

    public CardManagementPanel() {


        cardData = fetchCardData();
        tableModel = new CardTableModel(cardData);
        cardTable = new JTable(tableModel);

        // 设置表格外观
        cardTable.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cardTable.getTableHeader().setFont(new Font("微软雅黑", Font.BOLD, 14));
        cardTable.setRowHeight(30);
        cardTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 标题
        JLabel titleLabel = new JLabel("银行卡管理", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        add(titleLabel, BorderLayout.NORTH);

        // 选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setFont(new Font("微软雅黑", Font.PLAIN, 16));

        // 银行卡列表
        JPanel listPanel = new JPanel(new BorderLayout());

        listPanel.add(new JScrollPane(cardTable), BorderLayout.CENTER);

        // 底部按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        JButton deleteButton = createStyledButton("删除用户", Color.decode("#F44336"));
        JButton refreshButton = createStyledButton("刷新数据", Color.decode("#FF9800"));

        buttonPanel.add(deleteButton);
        buttonPanel.add(refreshButton);

        // 添加按钮事件处理
        deleteButton.addActionListener(this::deleteCard);
        refreshButton.addActionListener(e -> refreshData());

        add(buttonPanel, BorderLayout.SOUTH);


        // 开户功能
        JPanel openPanel = new JPanel(new GridLayout(0, 2, 10, 10));
        openPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

        // 开户表单字段
        CardInfo cardInfoNew = new CardInfo();
        cardInfoNew.setCustomerId(1);
        cardInfoNew.setSavingId(1);
        cardInfoNew.setOpenMoney(BigDecimal.valueOf(500));
        cardInfoNew.setPass("888888");


        List<String> customerNames = adminDAO.getAllCustomerID();
        List<String> depositTypes = adminDAO.getAllDepositType();
        List<String> openMoney = new ArrayList<>();
        openMoney.add("500");
        openMoney.add("800");
        openMoney.add("1000");
        List<String> beginPass = new ArrayList<>();
        beginPass.add("888888");

        // 选项列表（每个JComboBox对应的选项）

        // 第一个下拉框（直接转换）
        openPanel.add(new JLabel("客户ID:"));
        JComboBox<String> CustomerIDCombo = new JComboBox<>(customerNames.toArray(new String[0]));
        openPanel.add(CustomerIDCombo);
        CustomerIDCombo.addActionListener(e -> {
            cardInfoNew.setCustomerId(Integer.parseInt((String) CustomerIDCombo.getSelectedItem()));
            System.out.println("客户ID选择了" + CustomerIDCombo.getSelectedItem());
        });

        openPanel.add(new JLabel("存款类型:"));
        JComboBox<String> typeCombo = new JComboBox<>(depositTypes.toArray(new String[0]));
        openPanel.add(typeCombo);
        typeCombo.addActionListener(e -> {
            cardInfoNew.setSavingId(typeCombo.getSelectedIndex()+1);
            System.out.println("存款类型选择了" + typeCombo.getSelectedIndex()+1);
        });

        openPanel.add(new JLabel("开户金额:"));
        JComboBox<String> moneyCombo = new JComboBox<>(openMoney.toArray(new String[0]));
        openPanel.add(moneyCombo);
        moneyCombo.addActionListener(e -> {
            cardInfoNew.setOpenMoney((new BigDecimal(Integer.parseInt((String)  moneyCombo.getSelectedItem()))));
        });

        openPanel.add(new JLabel("初始密码:"));
        JComboBox<String> passCombo = new JComboBox<>(beginPass.toArray(new String[0]));
        openPanel.add(passCombo);
        passCombo.addActionListener(e -> {
           cardInfoNew.setPass((String)passCombo.getSelectedItem());
        });

        JButton openAccountBtn = new JButton("开户");
        openAccountBtn.setFont(new Font("微软雅黑", Font.BOLD, 16));
        openAccountBtn.setBackground(new Color(50, 150, 50));
        openAccountBtn.setForeground(Color.WHITE);

        openAccountBtn.addActionListener(e -> {
            String rtCardID = adminDAO.insertNewCardInfo(cardInfoNew);
            if(rtCardID != "wrong"){
                JOptionPane.showMessageDialog(this, "开户成功，账号为：" + rtCardID, "成功", JOptionPane.WARNING_MESSAGE);
            }else{
                JOptionPane.showMessageDialog(this, "开户失败，请检查信息后重试！", "错误", JOptionPane.WARNING_MESSAGE);

            }
        });


        openPanel.add(openAccountBtn);
        openPanel.add(new JLabel()); // 占位

        // 取消挂失功能
        JPanel reportLossPanel = new JPanel(new FlowLayout());
        reportLossPanel.add(new JLabel("输入卡号:"));
        JTextField cardField = new JTextField(20);
        reportLossPanel.add(cardField);

        JButton reportBtn = new JButton("取消挂失");
        reportBtn.setFont(new Font("微软雅黑", Font.BOLD, 14));
        reportBtn.setBackground(new Color(50, 150, 50));
        reportBtn.setForeground(Color.WHITE);

        reportBtn.addActionListener(e -> {
            int confirm = JOptionPane.showConfirmDialog(
                    this,
                    "确认取消挂失？",
                    "确认",
                    JOptionPane.YES_NO_OPTION
            );

            if (confirm == JOptionPane.YES_OPTION) {
                if(adminDAO.cancelLost(cardField.getText())){
                    JOptionPane.showMessageDialog(this, "取消挂失成功！", "成功", JOptionPane.WARNING_MESSAGE);
                }else {
                    JOptionPane.showMessageDialog(this, "程序出错，请重试！", "错误", JOptionPane.WARNING_MESSAGE);
                }
            }
        });
        reportLossPanel.add(reportBtn);

        openPanel.add(reportLossPanel);

        // 添加选项卡
        tabbedPane.addTab("银行卡列表", listPanel);
        tabbedPane.addTab("开户", openPanel);
        tabbedPane.addTab("卡状态管理", reportLossPanel);

        add(tabbedPane, BorderLayout.CENTER);
    }




    public static JButton createStyledButton(String text, Color bgColor) {
        JButton button = new JButton(text);
        button.setFont(new Font("微软雅黑", Font.BOLD, 14));
        button.setBackground(bgColor);
        button.setForeground(Color.WHITE);
        button.setFocusPainted(false);
        button.setPreferredSize(new Dimension(120, 40));
        return button;
    }

    private List<CardInfo> fetchCardData() {
        List<CardInfo> data = adminDAO.getCardInfo();
        return data;
    }



    private void deleteCard(ActionEvent e) {
        int selectedRow = cardTable.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(this, "请选择要删除的用户!", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        CardInfo card = cardData.get(selectedRow);
        int confirm = JOptionPane.showConfirmDialog(
                this,
                "确定要删除卡ID为 " + card.getCardId() + "的银行卡吗?",
                "确认删除",
                JOptionPane.YES_NO_OPTION
        );

        if (confirm == JOptionPane.YES_OPTION) {

            if(!adminDAO.deleteCardInfo(card.getCardId())){
                JOptionPane.showMessageDialog(this, "用户删除失败!", "错误", JOptionPane.INFORMATION_MESSAGE);
                return;
            }
            cardData.remove(selectedRow);
            tableModel.fireTableRowsDeleted(selectedRow, selectedRow);
            JOptionPane.showMessageDialog(this, "用户已删除!", "成功", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    private void refreshData() {
        cardData.clear();
        cardData.addAll(fetchCardData());
        tableModel.fireTableDataChanged();
        JOptionPane.showMessageDialog(this, "数据已刷新!", "成功", JOptionPane.INFORMATION_MESSAGE);
    }






}
